#include<stdlib.h>
#include<stdio.h>
#include<ucontext.h>
#include"threadStructure.h"
#include"thread.h"

int my_sem_init (my_sem_t * my_sem, unsigned int value){
  static int id = 0;
  if(!my_sem)
    return -1;
  my_sem->id = ++id ;
  my_sem->val = value;
  return 0;
}

int my_sem_wait (my_sem_t * my_sem){
  thread *th = getRunningThread();
  if(!my_sem || th->a_le_verou == TRUE)
    return -1;
  while(my_sem->val == 0)
    thread_yield();
  my_sem->val-- ;
  th->a_le_verou = TRUE;
  th->verou_id = my_sem->id;
  return 0;
}

int my_sem_post (my_sem_t * my_sem){
  thread *th = getRunningThread();
  th->verou_id = my_sem->id;
  if(!my_sem) 
    return -1;
  if(th->a_le_verou == FALSE || th->verou_id != my_sem->id)
    return -1;
  my_sem->val++;
  th->a_le_verou = FALSE;
  return 0;
}
